import * as WebBrowser from 'expo-web-browser';
import React, { Component } from 'react';
import {
  Image,
  Platform,
  ScrollView,
  StyleSheet,
  FlatList,
  Text,
  TouchableHighlight,
  TouchableOpacity,
  ActivityIndicator,
  View,
} from 'react-native';

import { MonoText } from '../components/StyledText';

export default class HomeScreen extends Component{
  constructor(props){
    super(props);
    this.state ={
      isLoading: true,
      taskList:[],
      curveList:[], // 曲线列表
      showList:[],
      todoList:[],
      reviewList:null,//展示的那个任务的任务复习时间列表
    };
  }
  componentDidMount(){
    this._fetchWebData();
  }

  async _fetchWebData(){
    try {
      let response = await fetch('https://dev.tencent.com/u/haomiaozhichen/p/project-resources/git/raw/master/ebbinghaus-review/task.json');
      console.log('response:',response);
      let res = null;
      if(response.status === 200){
        res = await response.json();
      }
      console.log('res:',res);
      let { taskList, curveList } = res;
      taskList.forEach((taskItem,taskIdx)=>{
        taskItem.key = 'task item ' + taskIdx;
        let curveObj = this.getCurve(taskItem.curveId,curveList);
        taskItem.curveName = curveObj.curveName;
        taskItem.curveId = curveObj.curveId;
        taskItem.curveDots = curveObj.curveDots;
        let list = [];

        taskItem.dateLearnTime = new Date(taskItem.strLearnTime +' 00:00');
        let learnTimeDate = taskItem.dateLearnTime.getDate();
        taskItem.curveDots.forEach((curveItem,idx)=>{
          let tempDate = new Date(taskItem.strLearnTime +' 00:00');
          tempDate.setDate(learnTimeDate + curveItem);
          tempDate = new Date(tempDate);
          list[idx] = {
            reviewTitle:'第' + (idx +1) + '次复习',
            dateReviewTime: tempDate,
            strReviewTime: tempDate.toLocaleDateString(),
            isDone:false
          }
        });
        taskItem.reviewTimeList =  list;
      });
      console.log('taskList:',taskList);
      let strToday = new Date().toLocaleDateString();
      let todoList =[];
      taskList.forEach((taskItem)=>{
        let reviewTimeList = taskItem.reviewTimeList;
        reviewTimeList.forEach((reviewItem,idx)=>{
          if(reviewItem.strReviewTime === strToday){
            todoList.push(taskItem);
          }
        })
      });
      this.setState({
        isLoading: false,
        taskList: taskList,
        curveList: curveList,
        todoList:todoList,
        showList:taskList
      });
    } catch (error) {
      console.error(error);
    }
  }
  
  getCurve(id,curveList){
    let obj = null;
    curveList.forEach((item)=>{
      if(item.curveId === id){
        obj = item;
      }
    });
    return obj
  }

  onListPress(item){
    console.log('onListPress item:', item);
    this.setState({reviewList:item.reviewTimeList})
  }
  onTabPress(type){
    console.log('onTabPress type:', type);
    this.setState((state) => ({
      showList: type === 'todo'? state.todoList:state.taskList
    }));
  }
  render(){
    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    }
    return (
      <View style={styles.container}>
        <View style={styles.headerView}>
          <TouchableHighlight onPress={() => this.onTabPress('todo')}>
            <Text>代办</Text>
          </TouchableHighlight>
          <TouchableHighlight onPress={() => this.onTabPress('task')}>
            <Text>任务</Text>
          </TouchableHighlight>
        </View>
        <View style={styles.reviewList}>
          <FlatList horizontal
              data={this.state.reviewList}
              extraData={this.state}
              renderItem={({item, index, separators}) => (
                <TouchableHighlight key={index}>
                  <View style={styles.reviewItem}>
                    <Text>{item.reviewTitle}</Text>
                    <Text>{item.strReviewTime}</Text>
                  </View>
                </TouchableHighlight>
              )}
              keyExtractor={(item, index) => index + '1'}>
          </FlatList>
        </View>
        <FlatList data={this.state.showList}
            extraData={this.state}
            renderItem={({item, index, separators}) => (
              <TouchableHighlight key={index} onPress={()=>this.onListPress(item) }>
                <View style={styles.taskView}>
                  <Text>{item.taskName}</Text>
                  <Text>首次学习：{item.strLearnTime}</Text>
                </View>
              </TouchableHighlight>
            )}
            keyExtractor={(item, index) => index + '1'}>
        </FlatList>
      </View>
    );
  }

}

HomeScreen.navigationOptions = {
  header: null
};

function DevelopmentModeNotice() {
  if (__DEV__) {
    const learnMoreButton = (
      <Text onPress={handleLearnMorePress} style={styles.helpLinkText}>
        Learn more
      </Text>
    );

    return (
      <Text style={styles.developmentModeText}>
        Development mode is enabled: your app will be slower but you can use
        useful development tools. {learnMoreButton}
      </Text>
    );
  } else {
    return (
      <Text style={styles.developmentModeText}>
        You are not in development mode: your app will run at full speed.
      </Text>
    );
  }
}

function handleLearnMorePress() {
  WebBrowser.openBrowserAsync(
    'https://docs.expo.io/versions/latest/workflow/development-mode/'
  );
}

function handleHelpPress() {
  WebBrowser.openBrowserAsync(
    'https://docs.expo.io/versions/latest/workflow/up-and-running/#cant-see-your-changes'
  );
}

const styles = StyleSheet.create({
  headerView:{
    paddingTop:25,
    paddingBottom:8,
    display:'flex',
    flexDirection:'row',
    justifyContent:'space-around',
    alignContent:'center',
    fontSize:45,
    fontWeight:'400'
  },
  reviewList:{
    height:60,
  },
  reviewItem:{
    display:'flex',
    padding:5
  },
  taskView:{
    display:'flex',
    flexDirection:'row',
    justifyContent:'space-between'
  },
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  developmentModeText: {
    marginBottom: 20,
    color: 'rgba(0,0,0,0.4)',
    fontSize: 14,
    lineHeight: 19,
    textAlign: 'center',
  },
  contentContainer: {
    paddingTop: 30,
  },
  welcomeContainer: {
    alignItems: 'center',
    marginTop: 10,
    marginBottom: 20,
  },
  welcomeImage: {
    width: 100,
    height: 80,
    resizeMode: 'contain',
    marginTop: 3,
    marginLeft: -10,
  },
  getStartedContainer: {
    alignItems: 'center',
    marginHorizontal: 50,
  },
  homeScreenFilename: {
    marginVertical: 7,
  },
  codeHighlightText: {
    color: 'rgba(96,100,109, 0.8)',
  },
  codeHighlightContainer: {
    backgroundColor: 'rgba(0,0,0,0.05)',
    borderRadius: 3,
    paddingHorizontal: 4,
  },
  getStartedText: {
    fontSize: 17,
    color: 'rgba(96,100,109, 1)',
    lineHeight: 24,
    textAlign: 'center',
  },
  tabBarInfoContainer: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    ...Platform.select({
      ios: {
        shadowColor: 'black',
        shadowOffset: { width: 0, height: -3 },
        shadowOpacity: 0.1,
        shadowRadius: 3,
      },
      android: {
        elevation: 20,
      },
    }),
    alignItems: 'center',
    backgroundColor: '#fbfbfb',
    paddingVertical: 20,
  },
  tabBarInfoText: {
    fontSize: 17,
    color: 'rgba(96,100,109, 1)',
    textAlign: 'center',
  },
  navigationFilename: {
    marginTop: 5,
  },
  helpContainer: {
    marginTop: 15,
    alignItems: 'center',
  },
  helpLink: {
    paddingVertical: 15,
  },
  helpLinkText: {
    fontSize: 14,
    color: '#2e78b7',
  },
});
